package com.example.smartclassroom.util;

import com.example.smartclassroom.entity.dto.LoginDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author lzy
 * @version 1.0
 * @description: jwttoken加密
 * @date 2023/5/1 15:41
 */
@Slf4j
public class Jwtutils {
    /**
     * 保存时间
     */
    public static final long EXPIRE = 60000 * 60 * 24 * 3;
    /**
     * 加密密钥
     */
    private static final String SECRET = "liuziyuan.net123.33333333";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "liuziyuan";
    /**
     * 主题是那个人发布的
     */
    private static final String SUBJETC = "liuziyuan";

    /**
     * token加密
     *
     * @param loginDTO
     * @return
     */
    public static String setToken(LoginDTO loginDTO) {
        String token = Jwts.builder().setSubject(SUBJETC)
                .claim("logInId", loginDTO.getLoginId())
                .claim("userName", loginDTO.getUserName())
                .claim("userType", loginDTO.getUserType().toString())
                //生成token时间
                .setIssuedAt(new Date())
                //token保存时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * token解密
     * 根据key获取值
     *
     * @param token
     * @return
     */
    public static Claims getJwt(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            log.info("token解密");
            return claims;
        }
        catch (Exception e) {
            log.error("token解密失败");
            return null;
        }
    }
}